#!/usr/bin/env python
# -*- coding:utf8 -*-
"""
Author : mafei
@Date   : 2019/12/02

"""
import redis

from mmonitor.common.vars import redis_server, redis_pwd, redis_port, redis_db

_CONN_POOL = None


def get_redis_conn():
    global _CONN_POOL
    if not _CONN_POOL:
        _CONN_POOL = redis.ConnectionPool(host=redis_server, port=redis_port,
                                          password=redis_pwd, db=redis_db)
    return redis.StrictRedis(connection_pool=_CONN_POOL)


class RedisConnector(object):
    """
    A simple object to store and pass database connection information.
    This makes the Simple Cache class a little more flexible, for cases
    where redis connection configuration needs customizing.
    """

    def __init__(self, host=redis_server, port=redis_port, password=redis_pwd, db=redis_db, limit=100000):
        self.host = host or '127.0.0.1'
        self.port = port or 6379
        self.db = db or 1
        self.password = password
        self.limit = limit

    def connect(self):
        """
        We cannot assume that connection will succeed, as such we use a ping()
        method in the redis client library to validate ability to contact redis.
        RedisNoConnException is raised if we fail to ping.
        :return: redis.StrictRedis Connection Object
        """
        conn = redis.StrictRedis(host=self.host, port=self.port, db=self.db, password=self.password, retry_on_timeout=True)
        try:
            conn.ping()
        except redis.ConnectionError as e:
            raise RedisNoConnException("Failed to create connection to redis",
                                       (self.host,
                                        self.port)
                                       )
        return conn

    @property
    def is_online(self):
        return True if self.connect().ping() else False


class CacheMissException(Exception):
    pass


class ExpiredKeyException(Exception):
    pass


class RedisNoConnException(Exception):
    pass


class DoNotCache(Exception):
    _result = None

    def __init__(self, result):
        super(DoNotCache, self).__init__()
        self._result = result

    @property
    def result(self):
        return self._result


if __name__ == "__main__":

    import sys

    if len(sys.argv) >= 2:
        print 'In order to change sensor address, '
        print 'you need modify variable `kafka_server` in file /opt/mmonitor/mmonitor.conf now !!!'
